package com.kanjj.mywebrtc.network;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.PeerConnection;
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;


class SimpleSdpObserver implements SdpObserver {

    private String TAG = "SimpleSdpObserver";
    private String type;
    private String socketId;

    public SimpleSdpObserver(String type, String socketId) {
        this.type = type;
        this.socketId = socketId;
    }

    public static final String OFFER = "offer";
    public static final String ANSWER = "answer";
    public static final String CANDIDATE = "candidate";
    public static final String DONE = "done";


    @Override
    public void onCreateSuccess(SessionDescription sessionDescription) {
        JSONObject message = new JSONObject();
        PeerConnection peerConnection = SocketClient.getInstance().peers.get(socketId);
        try {
            if (OFFER.equals(type)) {
                peerConnection.setLocalDescription(new SimpleSdpObserver(DONE, socketId), sessionDescription);
                message.put("type", OFFER);
                message.put("sdp", sessionDescription.description);
                SocketClient.getInstance().sendSignal(message, socketId);
            } else if (ANSWER.equals(type)) {
                peerConnection.setLocalDescription(new SimpleSdpObserver(DONE, socketId), sessionDescription);
                message.put("type", ANSWER);
                message.put("sdp", sessionDescription.description);
                SocketClient.getInstance().sendSignal(message, socketId);
            } else {
                Log.i(TAG, "SdpObserver: onCreateSuccess !");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSetSuccess() {
        System.out.println("=========== onSetSuccess ===========");
    }

    @Override
    public void onCreateFailure(String s) {
        System.out.println("=========== onCreateFailure ===========" + s);

    }

    @Override
    public void onSetFailure(String s) {
        System.out.println("=========== onSetFailure ===========" + s);
    }
}
